package org.colafries.admin.querybuilder.indexQuery;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.colafries.admin.entity.domain.index.LogicFactTableField;
import org.colafries.admin.querybuilder.entity.IndexQueryParamContext;
import org.colafries.admin.querybuilder.entity.IndexQuerySqlBuildContext;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author Ann
 * @version v1.0
 * @ClassName IndexQueryDimensionBuilder
 * @Description
 * @date Created in 2024/6/20
 **/
@Slf4j
public class DimensionBuilder implements IndexQuerySqlSegmentBuilder {


    @Override
    public void buildQueryParma(IndexQueryParamContext queryParamContext) {
        queryParamContext.getDimensionDTOList().forEach(dimensionDTO -> {
            Map<Long, LogicFactTableField> factTableFieldMap = queryParamContext.getFactTableFieldMap();
            List<LogicFactTableField> factTableFieldList = dimensionDTO.getFactTableFieldCodeList().stream()
                    .map(factTableFieldMap::get)
                    .collect(Collectors.toList());

            List<Long> factTableFieldListNew = factTableFieldList.stream()
                    // 只保留与逻辑表code同源的维度字段
                    .filter(factTableField -> factTableField.getLogicTableCode().equals(queryParamContext.getFactTable().getCode()))
                    .map(LogicFactTableField::getCode)
                    .collect(Collectors.toList());

            // 获取被排除的factTableField,从queryParamContext.factTableFieldMap移除
            List<Long> diff = dimensionDTO.getFactTableFieldCodeList().stream()
                    .filter(factTableCode -> !factTableFieldListNew.contains(factTableCode))
                    .collect(Collectors.toList());
            diff.forEach(queryParamContext.getFactTableFieldMap()::remove);

            // 覆盖 factTableFieldCodeList
            dimensionDTO.getFactTableFieldCodeList().clear();
            dimensionDTO.getFactTableFieldCodeList().addAll(factTableFieldListNew);
        });
    }

    @Override
    public void buildQuery(IndexQueryParamContext queryParamContext, IndexQuerySqlBuildContext sqlBuildContext) {
        Map<Long, LogicFactTableField> factTableFieldMap = queryParamContext.getFactTableFieldMap();
        queryParamContext.getDimensionDTOList().forEach(dimensionDTO -> {
            if (CollectionUtils.isEmpty(dimensionDTO.getFactTableFieldCodeList())) {
                return;
            }
            dimensionDTO.getFactTableFieldCodeList().forEach(factTableFieldCode -> {
                sqlBuildContext.getSelectColumns().add(factTableFieldMap.get(factTableFieldCode).getField());
                sqlBuildContext.getGroupByColumns().add(factTableFieldMap.get(factTableFieldCode).getField());
            });
        });
    }

}
